package com.dongpl.jar2mvn.service;

import com.dongpl.jar2mvn.pojo.MavenCoordinates;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

@Slf4j
@Service
public class MyService {

    public String testMvn(String mvnPath) {
        List<String> logResult = new ArrayList<>();
        try {
            String cmd = mvnPath + " --version";
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            reader.lines().forEach(item -> logResult.add(item.replaceAll("\u001B\\[[;\\d]*m", "")));
            process.waitFor();
        } catch (Exception e) {
            log.error("testMvn error", e);
        }
        // 日志大于2行，并且第一行以“Apache Maven”开头，第二行以“Maven home”开头
        if (logResult.size() > 2 && logResult.get(0).startsWith("Apache Maven") && logResult.get(1).startsWith("Maven home")) {
            return "测试成功！";
        }
        return "测试失败！";
    }

    public void installJar2Mvn(String mvnPath, String filePath, JTextArea resultOutput) {
        File file = new File(filePath);
        List<File> files = uploadFile(file);
        if (files.isEmpty()) {
            return;
        }
        for (File file1 : files) {
            resultOutput.append("开始导入" + file1.getAbsolutePath() + "\n");
            MavenCoordinates mavenCoordinates = extractPomCoordinates(file1);
            if (mavenCoordinates != null) {
                installToMaven(mvnPath, file1.getAbsolutePath(), mavenCoordinates, resultOutput);
            } else {
                resultOutput.append("获取" + file1.getAbsolutePath() + "信息失败！" + "\n");
            }
        }
    }

    public List<File> uploadFile(File chooseFile) {
        List<File> files = new ArrayList<>();
        if (chooseFile.isDirectory()) { // 处理文件夹中所有的jar文件
            System.out.println("你选择了文件夹: " + chooseFile.getAbsolutePath());
            List<File> allJars = findAllJarFiles(chooseFile);
            if (allJars.isEmpty()) {
                System.out.println("没有找到任何 jar 文件");
            } else {
                System.out.println("找到 jar 文件：" + allJars.size() + "个");
                files.addAll(allJars);
            }
        } else {
            System.out.println("你选择了 Jar 文件: " + chooseFile.getAbsolutePath());
            String name = chooseFile.getName().toLowerCase();
            if (!name.endsWith(".jar")) {
                JOptionPane.showMessageDialog(null, "只支持选择 Jar 文件或文件夹", "格式错误", JOptionPane.ERROR_MESSAGE);
            } else {
                files.add(chooseFile);
            }
        }
        return files;
    }

    private List<File> findAllJarFiles(File directory) {
        List<File> jarFiles = new ArrayList<>();
        if (directory != null && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        jarFiles.addAll(findAllJarFiles(f)); // 递归
                    } else if (f.getName().toLowerCase().endsWith(".jar")) {
                        jarFiles.add(f);
                    }
                }
            }
        }
        return jarFiles;
    }

    // 提取 Maven 坐标
    public static MavenCoordinates extractPomCoordinates(File jarFile) {
        try (JarFile jar = new JarFile(jarFile)) {
            for (ZipEntry entry : java.util.Collections.list(jar.entries())) {
                if (entry.getName().startsWith("META-INF/maven/") && entry.getName().endsWith("pom.properties")) {
                    try (InputStream is = jar.getInputStream(entry)) {
                        Properties props = new Properties();
                        props.load(is);
                        return new MavenCoordinates(
                                props.getProperty("groupId"),
                                props.getProperty("artifactId"),
                                props.getProperty("version")
                        );
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("解析 jar 失败：" + e.getMessage());
        }
        return null;
    }

    // 执行 deploy:deploy-file 命令上传
    public static void installToMaven(String mvnPath, String filePath, MavenCoordinates coords, JTextArea resultOutput) {
        String cmd = String.format("%s install:install-file -Dfile=%s -DgroupId=%s -DartifactId=%s -Dversion=%s -Dpackaging=jar",
                mvnPath, filePath, coords.getGroupId(), coords.getArtifactId(), coords.getVersion());
        resultOutput.append("执行命令: " + cmd + "\n");
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            reader.lines().forEach(item -> resultOutput.append(item.replaceAll("\u001B\\[", "") + "\n"));
            process.waitFor();
        } catch (Exception e) {
            log.error("执行导入异常", e);
        }
    }

    // 执行 deploy:deploy-file 命令上传
    public static void deployToMaven(File jarFile, MavenCoordinates coords) {
        String repoUrl = "http://localhost:8081/repository/maven-releases/"; // 修改为你的 Nexus 地址
        String repoId = "nexus-releases"; // Maven settings.xml 中配置的 server id
        String cmd = String.format("mvn deploy:deploy-file -DgroupId=%s -DartifactId=%s -Dversion=%s -Dpackaging=jar -Dfile=\"%s\" -DrepositoryId=%s -Durl=%s",
                coords.getGroupId(), coords.getArtifactId(), coords.getVersion(), jarFile.getAbsolutePath(), repoId, repoUrl);
        System.out.println("执行命令:\n" + cmd);
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            reader.lines().forEach(System.out::println);
            process.waitFor();
        } catch (Exception e) {
            log.error("执行导入异常", e);
        }
    }
}
